﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Dapper.Test.Entity;
using System.Data;

namespace Dapper.Test
{
    class Program
    {
        public static string ConnString = "server=.;uid=sa;pwd=11111111;database=Dapper;";
        static void Main(string[] args)
        {
            SqlConnection conn = new SqlConnection(Program.ConnString);
            conn.Open();
            //Transaction(conn);
            Query(conn);
        }
        /// <summary>
        /// 事务运行
        /// </summary>
        /// <param name="conn"></param>
        private static void Transaction(SqlConnection conn)
        {
            using (var tran = conn.BeginTransaction())
            {
                try
                {
                    conn.Execute("update type set name='类型Type' where id = 1", null,tran);
                    conn.Execute("update type1 set name = '类型Type1' where id = 1", null,tran);
                    tran.Commit();
                }
                catch (SqlException e)
                {
                    tran.Rollback();
                    throw e;
                }
            }
        }
        /// <summary>
        /// 执行多条语句查询
        /// </summary>
        /// <param name="conn"></param>
        private static void QueryMultiple(SqlConnection conn)
        {
            string sql="";
            var list=conn.QueryMultiple(sql, null);
            var data= list.Read<User>();
            var p = data.First<User>();
            
        }
        /// <summary>
        /// 一对多查询 最多嵌套4层
        /// </summary>
        /// <param name="conn"></param>
        private static void Query(SqlConnection conn)
        {
            
            string sql = "select u.* from [user] u left join [type] t on u.TypeID1=t.id left join type1 t1 on u.TypeID2=t1.id";
            var list = conn.Query<User, Type1, Entity.Type, User>(sql, (user, type1, type) => { user.Type1Model = type1; user.TypeModel = type; return user; }, null, null, true, "*", null, CommandType.Text).ToList();
            foreach (var item in list)
            {
                Console.WriteLine(item.TypeID2 + "------\n");
                Console.WriteLine(item.Type1Model.ID);
            }
            Console.ReadKey();
        }
  
    }
}
